package com.vrp3d.common.utils;

import com.vrp3d.common.enums.CommonEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 *
 * @author vrp3d
 */
public class JwtUtil {

    /**
     * 签发者
     */
    private static final String ISSUER = CommonEnum.JWT_ISSUE.getMsg();

    /**
     * 密钥
     */
    private static final String SECRET = CommonEnum.JWT_SECRET.getMsg();

    /**
     * 过期时间
     */
    private static final Long TTL_MILLIS = DateUtil.howManyMillisecondUntilMidnight();

    public static final String USERNAME = CommonEnum.JWT_USERNAME.getMsg();
    private static final String API_USER_ID = CommonEnum.JWT_USER_ID.getMsg();

    /**
     * 创建jwt
     *
     * @param username
     * @return
     */
    public static String createJwt(String username, Integer userId) {
        Map<String, Object> claims = new HashMap<>(3);
        claims.put(USERNAME, username);
        claims.put(API_USER_ID, userId);
        claims.put("jti", RandomUtil.getUuidWithOutHorizontalLine());
        Long currentTimeMillis = System.currentTimeMillis();
        JwtBuilder builder = Jwts.builder()
              .setClaims(claims)
              .setIssuer(ISSUER)
              .signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
              .setIssuedAt(new Date(currentTimeMillis))
              .setExpiration(new Date(currentTimeMillis + TTL_MILLIS));
        return builder.compact();
    }

    /**
     * 解析jwt
     *
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt) {
        return Jwts.parser().setSigningKey(SECRET.getBytes()).parseClaimsJws(jwt).getBody();
    }

}